from PySide6.QtWidgets import (QMainWindow, QWidget, QVBoxLayout, QHBoxLayout,
                               QLabel, QSplitter, QFrame, QPushButton, QLineEdit, QSizePolicy)
from PySide6.QtCore import Qt, QUrl, QSize
from PySide6.QtGui import QAction
from PySide6.QtWebEngineWidgets import QWebEngineView
from PySide6.QtWebEngineCore import QWebEngineSettings
import os
import sys


class SimpleMainWindow(QMainWindow):
    """
    带网页浏览器的主窗口 - 左右分栏布局
    左侧：网页控制面板
    右侧：网页浏览器
    """
    
    def __init__(self):
        super().__init__()
        
        # 设置WebEngine环境变量以解决GPU错误
        self.setup_webengine_environment()
        
        self.setup_window()
        self.setup_menu()
        self.setup_ui()
        
    def setup_window(self):
        """设置窗口基本属性"""
        self.setWindowTitle("网页浏览器")
        self.setGeometry(100, 100, 1200, 800)
        self.setMinimumSize(900, 600)
        
    def setup_menu(self):
        """设置菜单栏"""
        menubar = self.menuBar()
        
        # 帮助菜单
        help_menu = menubar.addMenu("帮助(&H)")
        about_action = QAction("关于(&A)", self)
        about_action.triggered.connect(self.on_about)
        help_menu.addAction(about_action)
        
    def setup_ui(self):
        """设置用户界面 - 左右分栏布局"""
        # 创建中央部件
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        
        # 创建主布局
        main_layout = QHBoxLayout(central_widget)
        main_layout.setContentsMargins(0, 0, 0, 0)
        main_layout.setSpacing(0)
        
        # 创建左右分栏器
        self.splitter = QSplitter(Qt.Horizontal)
        main_layout.addWidget(self.splitter)
        
        # 创建左侧面板（Agent对话界面）
        left_panel = self.create_left_panel()
        self.splitter.addWidget(left_panel)
        
        # 创建右侧面板（操作区域）
        right_panel = self.create_right_panel()
        self.splitter.addWidget(right_panel)
        
        # 设置分栏比例（左侧30%，右侧70%）
        self.splitter.setStretchFactor(0, 3)
        self.splitter.setStretchFactor(1, 7)
        self.splitter.setSizes([300, 700])
        
        # 监听分栏器变化事件
        self.splitter.splitterMoved.connect(self.on_splitter_moved)
        
        # 创建状态栏
        self.statusBar().showMessage("网页浏览器 - 就绪")
        
    def setup_webengine_environment(self):
        """设置WebEngine环境变量以解决GPU错误"""
        # 设置环境变量来禁用GPU加速，解决Chromium错误
        chromium_flags = [
            "--disable-gpu",
            "--disable-software-rasterizer", 
            "--disable-gpu-sandbox",
            "--disable-accelerated-2d-canvas",
            "--disable-accelerated-jpeg-decoding",
            "--disable-accelerated-mjpeg-decode",
            "--disable-accelerated-video-decode",
            "--disable-accelerated-video-encode",
            "--disable-web-security",
            "--disable-features=VizDisplayCompositor"
        ]
        
        # 设置环境变量
        os.environ["QTWEBENGINE_CHROMIUM_FLAGS"] = " ".join(chromium_flags)
        
        # 设置其他相关环境变量
        os.environ["QTWEBENGINE_DISABLE_SANDBOX"] = "1"
        os.environ["QTWEBENGINE_REMOTE_DEBUGGING"] = "0"
        
    def create_left_panel(self):
        """创建左侧网页控制面板"""
        left_widget = QFrame()
        left_widget.setStyleSheet("""
            QFrame {
                background-color: #f5f5f5;
                border-right: 1px solid #ddd;
            }
        """)
        
        # 左侧布局
        left_layout = QVBoxLayout(left_widget)
        left_layout.setContentsMargins(15, 15, 15, 15)
        left_layout.setSpacing(10)
        
        # 控制面板标题
        title_label = QLabel("🌐 网页控制")
        title_label.setAlignment(Qt.AlignCenter)
        title_label.setStyleSheet("""
            QLabel {
                font-size: 16px;
                font-weight: bold;
                color: #333;
                padding: 12px;
                background-color: #e3f2fd;
                border-radius: 5px;
                border: 1px solid #b3d8f0;
            }
        """)
        left_layout.addWidget(title_label)
        
        # 网址输入区域
        url_label = QLabel("网址：")
        url_label.setStyleSheet("font-weight: bold; color: #555;")
        left_layout.addWidget(url_label)
        
        self.url_input = QLineEdit()
        self.url_input.setPlaceholderText("请输入网址，如: https://www.baidu.com")
        self.url_input.setText("https://www.baidu.com")
        self.url_input.setStyleSheet("""
            QLineEdit {
                padding: 8px;
                border: 1px solid #ccc;
                border-radius: 5px;
                font-size: 12px;
                background-color: white;
            }
            QLineEdit:focus {
                border: 2px solid #007acc;
            }
        """)
        self.url_input.returnPressed.connect(self.navigate_to_url)
        left_layout.addWidget(self.url_input)
        
        # 导航按钮
        nav_button = QPushButton("🚀 打开网页")
        nav_button.setStyleSheet("""
            QPushButton {
                background-color: #007acc;
                color: white;
                border: none;
                padding: 10px;
                border-radius: 5px;
                font-weight: bold;
                font-size: 13px;
            }
            QPushButton:hover {
                background-color: #005a9e;
            }
            QPushButton:pressed {
                background-color: #004080;
            }
        """)
        nav_button.clicked.connect(self.navigate_to_url)
        left_layout.addWidget(nav_button)
        
        # 快捷网站按钮
        shortcuts_label = QLabel("🔗 快捷网站")
        shortcuts_label.setStyleSheet("font-weight: bold; color: #555; margin-top: 10px;")
        left_layout.addWidget(shortcuts_label)
        
        # 百度按钮
        baidu_btn = QPushButton("百度")
        baidu_btn.clicked.connect(lambda: self.load_url("https://www.baidu.com"))
        baidu_btn.setStyleSheet(self.get_shortcut_button_style("#4CAF50"))
        left_layout.addWidget(baidu_btn)
        
        # 腾讯按钮
        tencent_btn = QPushButton("腾讯")
        tencent_btn.clicked.connect(lambda: self.load_url("https://www.qq.com"))
        tencent_btn.setStyleSheet(self.get_shortcut_button_style("#FF9800"))
        left_layout.addWidget(tencent_btn)
        
        # GitHub按钮
        github_btn = QPushButton("GitHub")
        github_btn.clicked.connect(lambda: self.load_url("https://github.com"))
        github_btn.setStyleSheet(self.get_shortcut_button_style("#6B73FF"))
        left_layout.addWidget(github_btn)
        
        # 网页元素控制区域
        control_label = QLabel("🎛️ 网页控制")
        control_label.setStyleSheet("font-weight: bold; color: #555; margin-top: 15px;")
        left_layout.addWidget(control_label)
        
        # 搜索输入和按钮
        search_layout = QHBoxLayout()
        self.baidu_search_input = QLineEdit()
        self.baidu_search_input.setPlaceholderText("百度搜索内容…")
        self.baidu_search_input.setStyleSheet("font-size: 12px; padding: 4px; border-radius: 4px; border: 1px solid #ccc;")
        search_btn = QPushButton("🔍 搜索")
        search_btn.setStyleSheet("font-size: 12px; background-color: #2196F3; color: white; border: none; border-radius: 4px; padding: 6px 10px;")
        search_btn.clicked.connect(self.baidu_search)
        search_layout.addWidget(self.baidu_search_input)
        search_layout.addWidget(search_btn)
        search_widget = QWidget()
        search_widget.setLayout(search_layout)
        left_layout.addWidget(search_widget)
        
        # 控制按钮布局
        control_layout = QHBoxLayout()
        
        # 刷新按钮
        refresh_btn = QPushButton("🔄")
        refresh_btn.setToolTip("刷新页面")
        refresh_btn.clicked.connect(self.refresh_page)
        refresh_btn.setStyleSheet("""
            QPushButton {
                background-color: #2196F3;
                color: white;
                border: none;
                padding: 8px 12px;
                border-radius: 4px;
                font-weight: bold;
                font-size: 14px;
            }
            QPushButton:hover {
                background-color: #1976D2;
            }
        """)
        control_layout.addWidget(refresh_btn)
        
        # 后退按钮
        back_btn = QPushButton("⬅️")
        back_btn.setToolTip("后退")
        back_btn.clicked.connect(self.go_back)
        back_btn.setStyleSheet("""
            QPushButton {
                background-color: #FF9800;
                color: white;
                border: none;
                padding: 8px 12px;
                border-radius: 4px;
                font-weight: bold;
                font-size: 14px;
            }
            QPushButton:hover {
                background-color: #F57C00;
            }
        """)
        control_layout.addWidget(back_btn)
        
        # 前进按钮
        forward_btn = QPushButton("➡️")
        forward_btn.setToolTip("前进")
        forward_btn.clicked.connect(self.go_forward)
        forward_btn.setStyleSheet("""
            QPushButton {
                background-color: #4CAF50;
                color: white;
                border: none;
                padding: 8px 12px;
                border-radius: 4px;
                font-weight: bold;
                font-size: 14px;
            }
            QPushButton:hover {
                background-color: #45A049;
            }
        """)
        control_layout.addWidget(forward_btn)
        
        # 添加控制布局到主布局
        control_widget = QWidget()
        control_widget.setLayout(control_layout)
        left_layout.addWidget(control_widget)
        
        # 高级控制区域
        advanced_label = QLabel("⚙️ 高级控制")
        advanced_label.setStyleSheet("font-weight: bold; color: #555; margin-top: 15px;")
        left_layout.addWidget(advanced_label)
        
        # 隐藏图片按钮
        hide_images_btn = QPushButton("🖼️ 隐藏图片")
        hide_images_btn.setToolTip("隐藏页面中的所有图片")
        hide_images_btn.clicked.connect(self.hide_images)
        hide_images_btn.setStyleSheet("""
            QPushButton {
                background-color: #E91E63;
                color: white;
                border: none;
                padding: 8px;
                border-radius: 4px;
                font-weight: bold;
                font-size: 12px;
                margin: 2px;
            }
            QPushButton:hover {
                background-color: #C2185B;
            }
        """)
        left_layout.addWidget(hide_images_btn)
        
        # 显示图片按钮
        show_images_btn = QPushButton("🖼️ 显示图片")
        show_images_btn.setToolTip("显示页面中的所有图片")
        show_images_btn.clicked.connect(self.show_images)
        show_images_btn.setStyleSheet("""
            QPushButton {
                background-color: #00BCD4;
                color: white;
                border: none;
                padding: 8px;
                border-radius: 4px;
                font-weight: bold;
                font-size: 12px;
                margin: 2px;
            }
            QPushButton:hover {
                background-color: #0097A7;
            }
        """)
        left_layout.addWidget(show_images_btn)
        
        # 添加弹性空间
        left_layout.addStretch()
        
        return left_widget
        
    def create_right_panel(self):
        """创建右侧网页浏览器面板"""
        right_widget = QFrame()
        right_widget.setStyleSheet("""
            QFrame {
                background-color: white;
            }
        """)
        
        # 右侧布局
        right_layout = QVBoxLayout(right_widget)
        right_layout.setContentsMargins(2, 2, 2, 2)  # 减少边距，增加可用空间
        
        # 创建Web浏览器
        self.web_view = QWebEngineView()
        
        # 配置WebEngine设置以改善自适应性
        settings = self.web_view.settings()
        settings.setAttribute(QWebEngineSettings.WebAttribute.AutoLoadImages, True)
        settings.setAttribute(QWebEngineSettings.WebAttribute.JavascriptEnabled, True)
        settings.setAttribute(QWebEngineSettings.WebAttribute.LocalStorageEnabled, True)
        settings.setAttribute(QWebEngineSettings.WebAttribute.PluginsEnabled, True)
        
        # 优化渲染性能，减少黑屏问题
        settings.setAttribute(QWebEngineSettings.WebAttribute.ScrollAnimatorEnabled, False)
        settings.setAttribute(QWebEngineSettings.WebAttribute.ShowScrollBars, True)
        settings.setAttribute(QWebEngineSettings.WebAttribute.FullScreenSupportEnabled, True)
        
        # 设置初始缩放因子 - 让网页更好地适应容器
        self.web_view.setZoomFactor(0.7)  # 缩小到70%以适应容器
        
        # 设置最小尺寸和策略
        self.web_view.setMinimumSize(QSize(300, 200))
        self.web_view.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        
        # 监听页面加载状态
        self.web_view.loadStarted.connect(self.on_load_started)
        self.web_view.loadFinished.connect(self.on_load_finished)
        self.web_view.urlChanged.connect(self.on_url_changed)
        
        # 添加到布局
        right_layout.addWidget(self.web_view)
        
        # 设置初始页面
        self.web_view.setUrl(QUrl("https://www.baidu.com"))
        
        return right_widget
        

        

    def get_shortcut_button_style(self, color):
        """获取快捷按钮样式"""
        return f"""
            QPushButton {{
                background-color: {color};
                color: white;
                border: none;
                padding: 8px;
                border-radius: 4px;
                font-weight: bold;
                font-size: 12px;
                margin: 2px;
            }}
            QPushButton:hover {{
                background-color: {color}CC;
            }}
            QPushButton:pressed {{
                background-color: {color}AA;
            }}
        """
        
    def navigate_to_url(self):
        """导航到输入的URL"""
        url_text = self.url_input.text().strip()
        if url_text:
            # 如果没有协议，默认添加https://
            if not url_text.startswith(('http://', 'https://')):
                url_text = 'https://' + url_text
            self.load_url(url_text)
            
    def load_url(self, url):
        """加载指定URL"""
        self.web_view.setUrl(QUrl(url))
        self.url_input.setText(url)
        self.statusBar().showMessage(f"正在加载: {url}")
        
    def on_load_started(self):
        """页面开始加载"""
        self.statusBar().showMessage("正在加载网页...")
        
    def on_load_finished(self, success):
        """页面加载完成"""
        if success:
            current_url = self.web_view.url().toString()
            self.statusBar().showMessage(f"加载完成: {current_url}")
        else:
            self.statusBar().showMessage("页面加载失败")
            
    def on_url_changed(self, url):
        """URL变化时更新输入框"""
        self.url_input.setText(url.toString())
        
    def zoom_in(self):
        """放大网页"""
        current_zoom = self.web_view.zoomFactor()
        new_zoom = min(current_zoom + 0.1, 3.0)  # 最大放大到300%
        self.web_view.setZoomFactor(new_zoom)
        self.statusBar().showMessage(f"缩放: {int(new_zoom * 100)}%")
        
    def zoom_out(self):
        """缩小网页"""
        current_zoom = self.web_view.zoomFactor()
        new_zoom = max(current_zoom - 0.1, 0.3)  # 最小缩小到30%
        self.web_view.setZoomFactor(new_zoom)
        self.statusBar().showMessage(f"缩放: {int(new_zoom * 100)}%")
        
    def zoom_reset(self):
        """重置缩放到100%"""
        self.web_view.setZoomFactor(1.0)
        self.statusBar().showMessage("缩放: 100%")
        
    def fit_to_screen(self):
        """智能适应屏幕"""
        # 获取右侧面板的宽度
        panel_width = self.web_view.width()
        
        # 根据面板宽度计算合适的缩放比例
        # 假设标准网页宽度为1200px
        standard_width = 1200
        zoom_factor = panel_width / standard_width
        
        # 限制缩放范围在0.5到1.5之间
        zoom_factor = max(0.5, min(zoom_factor, 1.5))
        
        self.web_view.setZoomFactor(zoom_factor)
        self.statusBar().showMessage(f"自适应缩放: {int(zoom_factor * 100)}%")
        
    def on_splitter_moved(self, pos, index):
        """分栏器移动时的处理"""
        # 立即更新状态栏显示拖动状态
        self.statusBar().showMessage("正在调整面板大小...")
        
        # 延迟调用适应屏幕功能，避免频繁调整
        if hasattr(self, 'web_view'):
            from PySide6.QtCore import QTimer
            if not hasattr(self, '_splitter_timer'):
                self._splitter_timer = QTimer()
                self._splitter_timer.setSingleShot(True)
                self._splitter_timer.timeout.connect(self._auto_fit_to_screen)
            self._splitter_timer.start(100)  # 减少延迟到100ms，更快响应
            
    def resizeEvent(self, event):
        """窗口大小变化时的处理"""
        super().resizeEvent(event)
        
        # 延迟调用适应屏幕功能，避免频繁调整
        if hasattr(self, 'web_view'):
            # 使用QTimer延迟执行，避免在调整过程中频繁触发
            from PySide6.QtCore import QTimer
            if not hasattr(self, '_resize_timer'):
                self._resize_timer = QTimer()
                self._resize_timer.setSingleShot(True)
                self._resize_timer.timeout.connect(self._auto_fit_to_screen)
            self._resize_timer.start(300)  # 300ms后执行
            
    def _auto_fit_to_screen(self):
        """自动适应屏幕（内部方法）"""
        if hasattr(self, 'web_view') and self.web_view.width() > 0:
            # 获取右侧面板的宽度
            panel_width = self.web_view.width()
            
            # 根据面板宽度智能计算缩放比例
            if panel_width < 500:
                zoom_factor = 0.5
            elif panel_width < 600:
                zoom_factor = 0.6
            elif panel_width < 700:
                zoom_factor = 0.65
            elif panel_width < 800:
                zoom_factor = 0.7
            elif panel_width < 900:
                zoom_factor = 0.75
            elif panel_width < 1000:
                zoom_factor = 0.8
            elif panel_width < 1100:
                zoom_factor = 0.85
            else:
                zoom_factor = 0.9
                
            # 应用缩放并强制重绘
            self.web_view.setZoomFactor(zoom_factor)
            
            # 强制WebEngine重新渲染，减少黑屏
            self.web_view.page().runJavaScript("document.body.style.zoom = '{}';".format(zoom_factor))
            
            # 更新状态栏显示当前面板宽度和缩放比例
            self.statusBar().showMessage(f"面板宽度: {panel_width}px, 缩放: {int(zoom_factor * 100)}%")
        
    def on_about(self):
        """关于对话框"""
        from PySide6.QtWidgets import QMessageBox
        QMessageBox.about(self, "关于", 
                         "网页浏览器\n\n"
                         "基于 Python + PySide6 + WebEngine 开发\n"
                         "支持网页浏览和导航功能\n\n"
                         "技术栈: Python + PySide6 + WebEngine")
    
    def refresh_page(self):
        """刷新当前页面"""
        self.web_view.reload()
        self.statusBar().showMessage("正在刷新页面...")
    
    def go_back(self):
        """后退到上一页"""
        if self.web_view.history().canGoBack():
            self.web_view.back()
            self.statusBar().showMessage("后退到上一页")
        else:
            self.statusBar().showMessage("无法后退")
    
    def go_forward(self):
        """前进到下一页"""
        if self.web_view.history().canGoForward():
            self.web_view.forward()
            self.statusBar().showMessage("前进到下一页")
        else:
            self.statusBar().showMessage("无法前进")
    
    def hide_images(self):
        """隐藏页面中的所有图片"""
        js_code = """
        var images = document.getElementsByTagName('img');
        for (var i = 0; i < images.length; i++) {
            images[i].style.display = 'none';
        }
        """
        self.web_view.page().runJavaScript(js_code)
        self.statusBar().showMessage("已隐藏页面中的所有图片")
    
    def show_images(self):
        """显示页面中的所有图片"""
        js_code = """
        var images = document.getElementsByTagName('img');
        for (var i = 0; i < images.length; i++) {
            images[i].style.display = '';
        }
        """
        self.web_view.page().runJavaScript(js_code)
        self.statusBar().showMessage("已显示页面中的所有图片")

    def baidu_search(self):
        """使用百度搜索输入内容"""
        text = self.baidu_search_input.text().strip()
        if text:
            import urllib.parse
            query = urllib.parse.quote(text)
            url = f"https://www.baidu.com/s?wd={query}"
            self.load_url(url)
        else:
            self.statusBar().showMessage("请输入要搜索的内容")